package com.naodong.shenluntiku.mvp.view.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.naodong.shenluntiku.R;
import com.naodong.shenluntiku.di.component.DaggerCollectListComponent;
import com.naodong.shenluntiku.di.module.CollectListModule;
import com.naodong.shenluntiku.mvp.contract.CollectListContract;
import com.naodong.shenluntiku.mvp.model.bean.Analysis;
import com.naodong.shenluntiku.mvp.model.bean.CollectDetail;
import com.naodong.shenluntiku.mvp.model.bean.CollectType;
import com.naodong.shenluntiku.mvp.model.bean.EventBusTag;
import com.naodong.shenluntiku.mvp.model.bean.PagingBean;
import com.naodong.shenluntiku.mvp.model.bean.SubjectInfo;
import com.naodong.shenluntiku.mvp.model.data.api.CommonApi;
import com.naodong.shenluntiku.mvp.model.data.manager.BoxManager;
import com.naodong.shenluntiku.mvp.presenter.CollectListPresenter;
import com.naodong.shenluntiku.mvp.view.activity.AnalysisDetailActivityAutoBundle;
import com.naodong.shenluntiku.mvp.view.activity.SubjectInfoActivityAutoBundle;
import com.naodong.shenluntiku.mvp.view.adapter.CollectListAdapter;
import com.naodong.shenluntiku.mvp.view.widget.ErrorView;
import com.yatatsu.autobundle.AutoBundleField;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import me.shingohu.man.base.BaseMVPFragment;
import me.shingohu.man.di.component.AppComponent;
import me.shingohu.man.model.bean.SimpleEvent;
import me.shingohu.man.util.UiUtils;

import static com.naodong.shenluntiku.mvp.model.bean.CollectType.VIDEOANALYSISTYPE_ID;

/**
 * Created by hujie on 17/4/21.
 * <p>
 * 范文和解析的列表
 */

public class CollectListFragment extends BaseMVPFragment<CollectListPresenter> implements SwipeRefreshLayout.OnRefreshListener, CollectListContract.View {
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;


    @AutoBundleField(required = false)
    CollectType collectType;

    CollectListAdapter mAdapter;

    String moreUrl;

    @BindView(R.id.errorView)
    ErrorView errorView;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerCollectListComponent
                .builder()
                .appComponent(appComponent)
                .collectListModule(new CollectListModule(this)) //请将CollectModule()第一个首字母改为小写
                .build()
                .inject(this);
    }


    @Override
    protected void onViewCreated(Bundle savedInstanceState) {
        swipeRefreshLayout.setOnRefreshListener(this);
    }

    @Override
    protected boolean userAutoBindBundle() {
        return true;
    }

    private void initRecycleView() {
        UiUtils.configRecycleView(recyclerView, new LinearLayoutManager(getActivity()));
        mAdapter = new CollectListAdapter();
        mAdapter.bindToRecyclerView(recyclerView);
        mAdapter.disableLoadMoreIfNotFullPage();
        mAdapter.setPreLoadNumber(3);
        mAdapter.setOnLoadMoreListener(() -> {
            if (moreUrl != null) {
                mPresenter.requestCollectList(false, moreUrl);
            } else {
                mAdapter.loadMoreEnd();
            }
        }, recyclerView);

        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            CollectDetail collectDetail = (CollectDetail) adapter.getItem(position);
            if (collectDetail == null || collectDetail.getCollectDetail() == null) {
                return;
            }
            if (collectDetail.getItemType() == CollectDetail.VIDEO_ANALYSIS || collectDetail.getItemType() == CollectDetail.SUBJECT_ANALYSIS) {
                Analysis analysis = (Analysis) collectDetail.getCollectDetail();
                if (CollectType.VIDEOANALYSISTYPE_NAME.equals(collectDetail.getResourceType())) {
                    BoxManager.getInstance().putBoxCollect(analysis.getId(), VIDEOANALYSISTYPE_ID, true);
                    startActivity(AnalysisDetailActivityAutoBundle.builder(analysis.getDetailUrl(), analysis.getId(), VIDEOANALYSISTYPE_ID).build(getContext()));
                } else {
                    BoxManager.getInstance().putBoxCollect(analysis.getId(), CollectType.SUBJECTANALYSISTYPE_ID, true);
                    startActivity(AnalysisDetailActivityAutoBundle.builder(analysis.getDetailUrl(), analysis.getId(), CollectType.SUBJECTANALYSISTYPE_ID).build(getContext()));
                }
            } else if (collectDetail.getItemType() == CollectDetail.SUBJECT) {
                SubjectInfo subjectInfo = (SubjectInfo) collectDetail.getCollectDetail();

                BoxManager.getInstance().putBoxCollect(subjectInfo.getuSubId(), CollectType.SUBJECTTYPE_ID, true);
                startActivity(SubjectInfoActivityAutoBundle.builder(subjectInfo).build(getContext()));

            }

        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        firstRequest();
    }


    private void firstRequest() {
        String url = CommonApi.APP_URL + "api/favourite" + "?favourTypeId=" + collectType.getFavourTypeId();
        mPresenter.requestCollectList(true, url);
    }

    public void setCollectType(CollectType collectType) {
        this.collectType = collectType;
    }

    @Override
    protected int layoutId() {
        return R.layout.f_collect_list;
    }


    public static CollectListFragment getInstance(CollectType collectType) {
        CollectListFragment fragment = new CollectListFragment();
        fragment.setCollectType(collectType);
        return fragment;
    }


    @Override
    public void onRefresh() {
        firstRequest();
    }

    @Override
    public void showMessage(String msg) {

    }

    @Override
    public void onRequesrStart() {
        swipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void onRequestFinish() {
        swipeRefreshLayout.setRefreshing(false);
        if (mAdapter != null && mAdapter.isLoading()) {
            mAdapter.loadMoreComplete();
        }
    }

    private void checkHasMore(PagingBean pagingBean) {
        moreUrl = pagingBean.getNextUrl();
        if (moreUrl != null) {
            mAdapter.setEnableLoadMore(true);
            mAdapter.loadMoreComplete();
        } else {
            mAdapter.loadMoreEnd();
        }
    }


    @Override
    public void showEmptyView(String emptyText) {
        errorView.showEmptyView(emptyText);
    }

    @Override
    public void setCollectList(boolean isRefresh, PagingBean<List<CollectDetail>> listPagingBean) {
        if (mAdapter == null) {
            initRecycleView();
        }
        errorView.hideAllView();
        if (isRefresh) {
            mAdapter.setNewData(listPagingBean.getData());
        } else {
            if (listPagingBean.getData() != null && listPagingBean.getData().size() > 0) {
                mAdapter.addData(listPagingBean.getData());
            }
        }
        checkHasMore(listPagingBean);
    }

    @Override
    protected boolean userEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SimpleEvent event) {
        if (event.getType() == EventBusTag.NOTIFY_CANCLE_COLLECT) {
            int type = event.getIntEvent();
            int id = Integer.valueOf(event.getStrEvent());
            onNotifCancleCollect(type, id);
        }
    }


    //取消收藏的通知
    private void onNotifCancleCollect(int type, int id) {
        if (mAdapter != null) {
            List<CollectDetail> collectDetails = mAdapter.getData();
            int index = -1;
            if (type == CollectType.VIDEOANALYSISTYPE_ID || type == CollectType.SUBJECTANALYSISTYPE_ID) {
                for (CollectDetail collectDetail : collectDetails) {
                    if (collectDetail.getCollectDetail() instanceof Analysis) {
                        if (((Analysis) collectDetail.getCollectDetail()).getId() == id) {
                            index = collectDetails.indexOf(collectDetail);
                            break;
                        }
                    }
                }
            } else if (type == CollectType.SUBJECTTYPE_ID) {
                for (CollectDetail collectDetail : collectDetails) {
                    if (collectDetail.getCollectDetail() instanceof SubjectInfo) {
                        if (((SubjectInfo) collectDetail.getCollectDetail()).getuSubId() == id) {
                            index = collectDetails.indexOf(collectDetail);
                            break;
                        }
                        break;
                    }
                }
            }
            if (index > -1) {
                mAdapter.remove(index);
                if (mAdapter.getItemCount() == 0) {
                    errorView.showEmptyView("");
                }
            }
        }
    }


}
